package com.bubaiwantong.algorithms2.exchange;

public class QuickSort {


    public static void main(String[] args) {
        QuickSort quickSort = new QuickSort();
//        int[] arr = new int[]{9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
        int[] arr = new int[]{9, 8, 7, 6, 0, 5, 4, 3, 2, 1};
        quickSort.printArr(arr);
        quickSort.sort(arr, 0, arr.length - 1);
        quickSort.printArr(arr);
    }

    /**
     * 简单插入排序
     * 选择一个合适的位置插入
     *
     * @param arr
     */
    public void sort(int[] arr, int begin, int end) {
        if (begin >= end) {
            return;
        }
        int mid = partition(arr, begin, end);
        sort(arr, begin, mid - 1);
        sort(arr, mid + 1, end);
    }

    /**
     * 快速排序
     * 查找中间值
     *
     * @param arr
     * @param left
     * @param right
     * @return
     */
    public int partition(int[] arr, int left, int right) {
        int temp = arr[left];
        int low = left + 1;
        int high = right;
        while (low <= high) {
            while (low <= high && arr[low] < temp) {
                low++;
            }

            while (low <= high && arr[high] > temp) {
                high--;
            }
            if (low >= high) {
                break;
            }
            swap(arr, low, high);
        }
        swap(arr, left, high);
        return high;
    }

    public void printArr(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    public void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }


}
